package com.uzai.console.service.tb.tborder.impl;

import cn.hutool.core.date.DateTime;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.converters.longconverter.LongStringConverter;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.uzai.common.constants.UserExtKeys;
import com.uzai.common.entity.User;
import com.uzai.common.enums.*;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.result.ResponseCode;
import com.uzai.common.utils.EsIndexName;
import com.uzai.common.utils.Math;
import com.uzai.console.common.ResponseMsg;
import com.uzai.console.common.UzaiRespVo;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.common.utils.ZipUtils;
import com.uzai.console.component.excel.template.TbRefundOrderExcelDemo;
import com.uzai.console.config.UzaiConsoleSysConfig;
import com.uzai.console.constant.CacheKey;
import com.uzai.console.constant.Const;
import com.uzai.console.constant.ES.ElasticsearchUtil;
import com.uzai.console.dto.feign.alarm.AlarmMsgFeignDto;
import com.uzai.console.dto.feign.orderreport.OrderReportDto;
import com.uzai.console.dto.feign.tborder.TbOrderBindDto;
import com.uzai.console.dto.feign.tborder.TbOrderSettledDto;
import com.uzai.console.dto.feign.tborder.TbOrderUnbindDto;
import com.uzai.console.dto.feign.tborder.TbOrderUnfreezeDto;
import com.uzai.console.dto.orderpull.OrderPullQuery;
import com.uzai.console.dto.tb.tborder.*;
import com.uzai.console.dto.tb.tbtoken.TbTokenQuery;
import com.uzai.console.entity.*;
import com.uzai.console.entity.es.PriRuleVo;
import com.uzai.console.entity.es.RewardVo;
import com.uzai.console.enums.ExportInfoTypeEnum;
import com.uzai.console.enums.OrderPullPlatformEnum;
import com.uzai.console.enums.SmsType;
import com.uzai.console.mapper.*;
import com.uzai.console.service.CommonService;
import com.uzai.console.service.cms.CmsParamReplaceService;
import com.uzai.console.service.device.DeviceService;
import com.uzai.console.service.exportinfo.ExportInfoService;
import com.uzai.console.service.feign.HistoryDataFeignService;
import com.uzai.console.service.feign.TbOrderFeignService;
import com.uzai.console.service.feign.UzaiBroadcastFeignService;
import com.uzai.console.service.feign.dto.HistoryTbOrderOptDto;
import com.uzai.console.service.rocketmq.NoticeMsgPushProducerService;
import com.uzai.console.service.tb.tborder.TbOrderService;
import com.uzai.console.service.tb.tborder.TbOrderSyncService;
import com.uzai.console.service.user.UserService;
import com.uzai.console.service.useraccdetail.UserAccDetailService;
import com.uzai.console.vo.exportinfo.ExportAmountVo;
import com.uzai.console.vo.login.LoginVo;
import com.uzai.console.vo.order.BaseOrderVo;
import com.uzai.console.vo.profit.ladderratio.LadderRatioInfoVo;
import com.uzai.console.vo.profit.normalrewardrule.NormalRewardRuleInfoVo;
import com.uzai.console.vo.profit.nuserrewardrule.NuserRewardRuleInfoVo;
import com.uzai.console.vo.tb.tborder.TbOrderExport;
import com.uzai.console.vo.tb.tborder.TbOrderInfoVo;
import com.uzai.console.vo.tb.tborder.TbOrderReportVo;
import com.uzai.console.vo.tb.tborder.TbOrderTokenVo;
import com.uzai.console.vo.tb.tbpunishorder.TbPunishOrderExport;
import org.apache.commons.lang3.StringUtils;
import org.apache.tools.zip.ZipOutputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * 运营商基本配置
 * @author liuqi
 * @date 2021年08月13日 11:34
 */
@Service
public class TbOrderServiceImpl extends CommonService implements TbOrderService {

    Logger logger = LoggerFactory.getLogger(TbOrderServiceImpl.class);

    @Autowired
    private TbOrderMapper tbOrderMapper;
    @Autowired
    private TbTokenMapper tbTokenMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private TbOrderSyncService tbOrderSyncService;
    @Autowired
    private WechatUserMapper wechatUserMapper;
    @Autowired
    private UserTypeMapper userTypeMapper;
    @Autowired
    private TbOrderFeignService tbOrderFeignService;
    @Autowired
    private UserService userService;
    @Autowired
    private ElasticsearchUtil elasticsearchUtil;
    @Autowired
    private LadderRatioGroupMapper ladderRatioGroupMapper;
    @Autowired
    private NormalRewardRuleMapper normalRewardRuleMapper;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private NuserRewardRuleGroupMapper nuserRewardRuleGroupMapper;
    @Autowired
    private UzaiBroadcastFeignService uzaiBroadcastFeignService;
    @Autowired
    private HistoryDataFeignService historyDataFeignService;
    @Autowired
    private ConfigPlanMapper configPlanMapper;
    @Autowired
    private SysPluginMapper sysPluginMapper;
    @Autowired
    private CmsParamReplaceService cmsParamReplaceService;
    @Autowired
    private NoticeMsgPushProducerService noticeMsgPushProducerService;
    @Autowired
    private UserAccDetailService userAccDetailService;
    @Autowired
    private UzaiConsoleSysConfig uzaiConsoleSysConfig;
    @Autowired
    private SysConfigMapper sysConfigMapper;
    @Autowired
    private MerchantMapper merchantMapper;
    @Autowired
    private ExportInfoService exportInfoService;
    @Autowired
    private OrderPullMapper orderPullMapper;

    /**
     * 查询淘宝订单列表
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param param
     * @return null
     */
    public Page<TbOrderInfoVo> findTbOrderList(TbOrderQuery param){

        logger.info("--TbOrderQuery-- dto={}" + JSONObject.toJSONString(param));

        //判断子账号的机器人列表参数,是否不为空，则子账号查询，机器人查询条件以子账号负责的机器人列表为主
        List<Long> subDeviceUniqueIdList = param.getSubDeviceUniqueIdList();
        if(subDeviceUniqueIdList != null && subDeviceUniqueIdList.size() > 0){
            //查询机器人列表参数，是否不为空
            List<Long> deviceUniqueIdList = param.getDeviceUniqueIdList();
            if(deviceUniqueIdList != null && deviceUniqueIdList.size() > 0){
                //创建临时查询列表变量，存放子账号关联的机器人
                List<Long> deviceUniqueIdList_new = new ArrayList<>();
                for (Long deviceUniqueId : deviceUniqueIdList) {
                    //如果子账号机器人列表不包括此机器人，则不允许查询，去掉此机器人
                    if(subDeviceUniqueIdList.contains(deviceUniqueId)){
                        deviceUniqueIdList_new.add(deviceUniqueId);
                    }
                }
                //重新赋值子账号平台机器人列表,清空子账号机器人列表参数，重新赋值机器人重新列表参数
                param.setSubDeviceUniqueIdList(null);
                param.setDeviceUniqueIdList(deviceUniqueIdList_new);
            }
        }

        //新建返回到页面的LIST对象
        List<TbOrderInfoVo> tbOrderInfoVoList = new ArrayList<>();

        Page<TbOrder> page = new Page<>();
        param.convert(page);

        List<TbOrder> tbOrderList = null;
        if (super.checkStartEndTimeIsHistoryQuery(param.getQueryStartTime(), param.getQueryEndTime(), param.getQueryMonth())) {
            String tableSuffix = DateTime.of(param.getQueryEndTime() * 1000L).toString("yyMM");
            UzaiRespVo<Page<TbOrder>> tbOrderListRes = historyDataFeignService.pageTbHistoryOrder(tableSuffix, param);
            if (tbOrderListRes.getCode() != 200) {
                throw new BusinessException("淘宝订单列表查询失败");
            }
            if(tbOrderListRes.getData() != null){
                tbOrderList = tbOrderListRes.getData().getRecords();
                page.setTotal(tbOrderListRes.getData().getTotal());
            }
        }
        // 反之查询90天内的订单数据
        else {
            if(param.getSize() > 100){
                param.setSize(100);
            }
            tbOrderList =  tbOrderMapper.findByList(page, param);
        }

        if(null != tbOrderList && tbOrderList.size() > 0){
            for (TbOrder tbOrder : tbOrderList){

                TbOrderInfoVo tbOrderInfoVo = new TbOrderInfoVo();
                BeanUtils.copyProperties(tbOrder, tbOrderInfoVo);
                //查询机器人信息
                Device device = deviceService.findDeviceInfoByDeviceUniqueId(tbOrder.getDeviceUniqueId(), tbOrder.getDeviceType(), tbOrder.getMerId());
                if(device != null){
                    tbOrderInfoVo.setDeviceId(device.getDeviceId());
                    tbOrderInfoVo.setDeviceName(device.getDeviceName());
                    tbOrderInfoVo.setDeviceRemark(device.getDeviceRemark());
                }

                //订单状态
                if(tbOrder.getStatus() != null){
                    OrderStatusEnum orderStatusEnum = OrderStatusEnum.getById(tbOrder.getStatus());
                    if(orderStatusEnum != null){
                        tbOrderInfoVo.setStatusName(orderStatusEnum.getDesc());
                    }
                }
                tbOrderInfoVoList.add(tbOrderInfoVo);
            }
        }
        //返回到页面分页对象
        Page<TbOrderInfoVo> pageVo = new Page<>();
        BeanUtils.copyProperties(page, pageVo);
        pageVo.setRecords(tbOrderInfoVoList);
        //将分页信息复制到返回到页面的分页MO当中
        return pageVo;
    }

    /**
     * 查询淘宝订单详情
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param tbOrderDto
     * @return null
     */
    public TbOrderInfoVo findTbOrderInfo(TbOrderDto tbOrderDto){
        //返回到页面的VO对象
        TbOrderInfoVo tbOrderInfoVo = new TbOrderInfoVo();

        if(tbOrderDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入id");
        }

        TbOrder tbOrder = tbOrderMapper.selectById(tbOrderDto.getId(), tbOrderDto.getMerId());

        //如果为空，则从历史订单中查询
        if(tbOrder == null){
            if(tbOrderDto.getCreatedt() == null){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入订单创建时间");
            }
            String tableSuffix = DateTime.of(tbOrderDto.getCreatedt() * 1000L).toString("yyMM");
            UzaiRespVo<TbOrder> uzaiRespVo = historyDataFeignService.getTbOrder(tableSuffix, tbOrderDto.getId(), tbOrderDto.getMerId());
            if(uzaiRespVo != null && uzaiRespVo.getData() != null){
                tbOrder = uzaiRespVo.getData();
            }
        }

        if(tbOrder == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该订单不存在");
        }

        //将查询到的数据复制到页面VO中
        BeanUtils.copyProperties(tbOrder, tbOrderInfoVo);

        //订单状态
        if(tbOrder.getStatus() != null){
            OrderStatusEnum orderStatusEnum = OrderStatusEnum.getById(tbOrder.getStatus());
            if(orderStatusEnum != null){
                tbOrderInfoVo.setStatusName(orderStatusEnum.getDesc());
            }
        }

        //查询机器人信息
        Device device = deviceService.findDeviceInfoByDeviceUniqueId(tbOrder.getDeviceUniqueId(), tbOrder.getDeviceType(), tbOrder.getMerId());
        if(device != null){
            tbOrderInfoVo.setDeviceId(device.getDeviceId());
            tbOrderInfoVo.setDeviceName(device.getDeviceName());
            tbOrderInfoVo.setDeviceRemark(device.getDeviceRemark());
        }

        //通过会员ID查询会员类型信息
        User user = userService.findUserInfo(tbOrder.getUserId(), tbOrder.getDeviceType(), tbOrderDto.getMerId());
        if(user != null){
            tbOrderInfoVo.setIdentity(user.getIdentity());
            IdentityEnum identityEnum = IdentityEnum.getById(user.getIdentity());
            if(identityEnum != null){
                tbOrderInfoVo.setIdentityName(identityEnum.getDesc());
            }
            UserType userType = userTypeMapper.selectById(user.getUserType(), tbOrderDto.getMerId());
            if(userType != null){
                tbOrderInfoVo.setUserTypeName(userType.getName());
            }
        }

        //通过联盟alimmId查询联盟信息，得到联盟账号名称
        if(tbOrder.getAlimmTbId() != null ){
            TbToken tbToken = null;
            if(uzaiConsoleSysConfig.getTbAppkeyDg().equals(tbOrder.getAppKey())){
                tbToken = tbTokenMapper.selectByUserIdAndTurnLink(tbOrder.getAlimmTbId(), 1);
            }else{
                tbToken = tbTokenMapper.selectByUserIdAndTurnLink(tbOrder.getAlimmTbId(), 0);
            }
            if(tbToken != null){
                //备注
                String remark = tbToken.getRemark();
                if(Tools.getInteger(tbToken.getTurnlink()).intValue() == 1){
                    if(StringUtils.isNotBlank(tbToken.getRemark())){
                        remark =  "导购_" + remark;
                    }else{
                        remark =   "导购";
                    }
                }else{
                    if(StringUtils.isNotBlank(tbToken.getRemark())){
                        remark =  "返利_" + remark;
                    }else{
                        remark =   "返利";
                    }
                }
                String value = tbToken.getUserName();
                if(StringUtils.isNotBlank(remark)){
                    value = value + "（" + remark + "）";
                }
                tbOrderInfoVo.setAlimmName(value);
            }
        }

        //设置PID
        String pid = "mm" + "_" + tbOrder.getPubId() + "_" + tbOrder.getSiteId() +  "_" + tbOrder.getAdzoneId();
        tbOrderInfoVo.setPid(pid);

        //封装分佣信息
        //ESID为运营商id_父订单号_子订单号
        String es_id = tbOrder.getMerId() + "_" + tbOrder.getParentOrderNo() + "_" + tbOrder.getChildOrderNo();

        try {
            Map<String, Object> orderEsMap = elasticsearchUtil.searchDataById(EsIndexName.UZAI_ORDER_REWARD_INFO, es_id, null);
            RewardVo rewardVo = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(orderEsMap)), RewardVo.class);
            if(rewardVo != null){

                //定向规则
                PriRuleVo priRule = rewardVo.getPriRule();
                if(priRule != null){
                    //阶梯规则组ID
                    LadderRatioInfoVo ladderRatio = priRule.getLadderRatio();
                    if(ladderRatio != null){
                        Long groupId = ladderRatio.getGroupId();
                        if(groupId != null){
                            LadderRatioGroup ladderRatioGroup = ladderRatioGroupMapper.selectById(groupId, tbOrderDto.getMerId());
                            if(ladderRatioGroup != null){
                                ladderRatio.setGroupName(ladderRatioGroup.getName());
                            }
                        }

                    }
                }

                //杀熟规则
                NuserRewardRuleInfoVo nuserRewardRule = rewardVo.getNuserRewardRule();
                if(nuserRewardRule != null){
                    //杀熟规则组
                    Long nuserRewardGroupId = nuserRewardRule.getGroupId();
                    if(nuserRewardGroupId != null){
                        NuserRewardRuleGroup nuserRewardRuleGroup = nuserRewardRuleGroupMapper.selectById(nuserRewardGroupId, tbOrderDto.getMerId());
                        if(nuserRewardRuleGroup != null){
                            nuserRewardRule.setGroupName(nuserRewardRuleGroup.getName());
                        }
                    }

                    //分佣规则ID
                    Long normalRewardRuleId = nuserRewardRule.getNormalRewardRuleId();
                    if(normalRewardRuleId != null){
                        NormalRewardRule normalRewardRule = normalRewardRuleMapper.selectById(normalRewardRuleId, tbOrderDto.getMerId());
                        if(normalRewardRule != null){
                            nuserRewardRule.setNormalRewardRuleName(normalRewardRule.getName());
                        }
                    }

                    //阶梯规则组ID
                    LadderRatioInfoVo ladderRatio = nuserRewardRule.getLadderRatio();
                    if(ladderRatio != null){
                        Long groupId = ladderRatio.getGroupId();
                        if(groupId != null){
                            LadderRatioGroup ladderRatioGroup = ladderRatioGroupMapper.selectById(groupId, tbOrderDto.getMerId());
                            if(ladderRatioGroup != null){
                                ladderRatio.setGroupName(ladderRatioGroup.getName());
                            }
                        }

                    }
                }

                //分佣规则
                NormalRewardRuleInfoVo normalRewardRule = rewardVo.getNormalRewardRule();
                if(normalRewardRule != null){

                    //阶梯规则组ID
                    LadderRatioInfoVo ladderRatio = normalRewardRule.getLadderRatio();
                    if(ladderRatio != null){
                        Long groupId = ladderRatio.getGroupId();
                        if(groupId != null){
                            LadderRatioGroup ladderRatioGroup = ladderRatioGroupMapper.selectById(groupId, tbOrderDto.getMerId());
                            if(ladderRatioGroup != null){
                                ladderRatio.setGroupName(ladderRatioGroup.getName());
                            }
                        }
                    }

                    //计算分佣总佣金（扣除N%之后的佣金）
                    //订单总佣金
                    Double commission = tbOrder.getCommission();
                    if(commission != null){
                        //扣除N%的计算总佣金（默认等于订单总佣金）
                        Double rewardSub = commission;
                        //分佣规则里配置的扣除N%比例
                        Double rewardSubRatio = normalRewardRule.getRewardSubRatio();
                        if(rewardSubRatio != null){
                            rewardSub = Math.mul(commission, (1 - normalRewardRule.getRewardSubRatio()/100));
                        }
                        normalRewardRule.setCalculateCommission(rewardSub);
                    }
                }

                //买家
                RewardVo.ReDetail reDetail = rewardVo.getReUser();
                if(reDetail != null){
                    User reUser = userService.findUserInfo(reDetail.getUserId(), tbOrder.getDeviceType(), tbOrderDto.getMerId());
                    if(reUser != null){
                        reDetail.setUserName(reUser.getNickName());
                    }
                }

                //合伙人
                RewardVo.ReDetail rePartner = rewardVo.getRePartner();
                if(rePartner != null){
                    User rePartnerUser = userService.findUserInfo(rePartner.getUserId(), tbOrder.getDeviceType(), tbOrderDto.getMerId());
                    if(rePartnerUser != null){
                        rePartner.setUserName(rePartnerUser.getNickName());
                    }
                }

                //代理人
                RewardVo.ReDetail reAgent = rewardVo.getReAgent();
                if(reAgent != null){
                    User reAgentUser = userService.findUserInfo(reAgent.getUserId(), tbOrder.getDeviceType(), tbOrderDto.getMerId());
                    if(reAgentUser != null){
                        reAgent.setUserName(reAgentUser.getNickName());
                    }
                }

                //上级代理人
                RewardVo.ReDetail reSlAgent = rewardVo.getReSlAgent();
                if(reSlAgent != null){
                    User reSlAgentUser = userService.findUserInfo(reSlAgent.getUserId(), tbOrder.getDeviceType(), tbOrderDto.getMerId());
                    if(reSlAgentUser != null){
                        reSlAgent.setUserName(reSlAgentUser.getNickName());
                    }
                }

                //买家上级
                RewardVo.ReDetail reParent = rewardVo.getReParent();
                if(reParent != null){
                    User reParentUser = userService.findUserInfo(reParent.getUserId(), tbOrder.getDeviceType(), tbOrderDto.getMerId());
                    if(reParentUser != null){
                        reParent.setUserName(reParentUser.getNickName());
                    }
                }

                //买家上上级
                RewardVo.ReDetail reSlParent = rewardVo.getReSlParent();
                if(reSlParent != null){
                    User reSlParentUser = userService.findUserInfo(reSlParent.getUserId(), tbOrder.getDeviceType(), tbOrderDto.getMerId());
                    if(reSlParentUser != null){
                        reSlParent.setUserName(reSlParentUser.getNickName());
                    }
                }

                //N级
                List<RewardVo.ReDetail> reOthers = rewardVo.getReOthers();
                if(reOthers != null && reOthers.size() > 0){
                    for (RewardVo.ReDetail reOther : reOthers){
                        if(reOther != null){
                            User reOtherUser = userService.findUserInfo(reOther.getUserId(), tbOrder.getDeviceType(), tbOrderDto.getMerId());
                            if(reOtherUser != null){
                                reOther.setUserName(reOtherUser.getNickName());
                            }
                        }
                    }
                }

            }

            tbOrderInfoVo.setRewardVo(rewardVo);
        }catch(Exception e){
            logger.error("-----order uzai_order_reward_info of ES is not exit {}", e.getMessage());
        }

        return  tbOrderInfoVo;
    }

    /**
     * 查询淘宝订单统计信息
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param tbOrderQuery
     * @return null
     */
    public TbOrderReportVo findTbOrderRepot(TbOrderQuery tbOrderQuery){
        TbOrderReportVo tbOrderReportVo = null;
        //获取订单状态枚举,不包括失效订单
        OrderStatusEnum[] orderStatusEnums = OrderStatusEnum.values();
        if(orderStatusEnums != null && orderStatusEnums.length > 0 ){
            //查询订单状态
            List<Integer> statusList = tbOrderQuery.getStatusList();
            if(statusList == null || statusList.size() == 0){
                statusList = new ArrayList<>();
                for (OrderStatusEnum orderStatusEnum : orderStatusEnums) {
                    //不包括失效订单
                    if(orderStatusEnum.getValue().intValue() != OrderStatusEnum.STATUS_INVALID.getValue().intValue()){
                        statusList.add(orderStatusEnum.getValue());
                    }
                }
            }else{
                statusList.remove(OrderStatusEnum.STATUS_INVALID.getValue().intValue());
            }
            tbOrderQuery.setStatusList(statusList);
        }

        //查询历史数据统计
        if (super.checkStartEndTimeIsHistoryQuery(tbOrderQuery.getQueryStartTime(), tbOrderQuery.getQueryEndTime(), tbOrderQuery.getQueryMonth())) {
            String tableSuffix = DateTime.of(tbOrderQuery.getQueryEndTime() * 1000L).toString("yyMM");
            UzaiRespVo<TbOrderReportVo> uzaiRespVo = historyDataFeignService.getTbOrderStatistics(tableSuffix, tbOrderQuery);
            if (uzaiRespVo.getCode() != 200) {
                throw new BusinessException("查询淘宝订单统计失败");
            }
            tbOrderReportVo = uzaiRespVo.getData();
        }else{//查询90天内的订单数据统计
            tbOrderReportVo = tbOrderMapper.findTbOrderRepot(tbOrderQuery);
        }
        return tbOrderReportVo;
    }

    /**
     * 淘宝订单删除
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param tbOrderDelDto
     * @return null
     */
    public Boolean delTbOrder(TbOrderDelDto tbOrderDelDto){

        TbOrder tbOrder = tbOrderMapper.selectById(tbOrderDelDto.getId(), tbOrderDelDto.getMerId());
        if(tbOrder == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.ORDER_IS_NULL);
        }
        tbOrderMapper.deleteById(tbOrderDelDto.getId(), tbOrderDelDto.getMerId());


        //发送MQ，修改订单统计数据
        if(tbOrder.getUserId() != null){
            String userExtKey_tb = null;
            String userExtKey = null;
            if(tbOrder.getStatus().intValue() == OrderStatusEnum.STATUS_PAID_VALUE) { //付款订单
                userExtKey_tb = UserExtKeys.TbPayOrderCount;
                userExtKey = UserExtKeys.PayOrderCount;
            }else if(tbOrder.getStatus().intValue() == OrderStatusEnum.STATUS_SETTLED_VALUE){ //结算状态
                userExtKey_tb = UserExtKeys.TbSettleOrderCount;
                userExtKey = UserExtKeys.SettleOrderCount;
            }

            //不等于空，才发送MQ
            if(StringUtils.isNotBlank(userExtKey_tb)){
                OrderReportDto orderReportDto = new OrderReportDto();
                orderReportDto.setId(Tools.getStr(tbOrder.getParentOrderNo()) + Tools.getStr(tbOrder.getChildOrderNo()));
                orderReportDto.setKeys(Lists.newArrayList(userExtKey_tb, userExtKey));
                orderReportDto.setMerId(tbOrder.getMerId());
                orderReportDto.setUserId(tbOrder.getUserId());
                orderReportDto.setVal(-1);
                noticeMsgPushProducerService.sendOrderReportAsync(orderReportDto);
            }
        }

        return true;

    }

    /**
     * 确认收货
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param tbOrderDto
     * @return null
     */
    public Boolean confirmReceive(TbOrderDto tbOrderDto){

        if(tbOrderDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        //查询淘宝订单
        TbOrder tbOrder = tbOrderMapper.selectById(tbOrderDto.getId(), tbOrderDto.getMerId());

        if(tbOrder == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.ORDER_IS_NULL);
        }

        //查询用户是否存在
        if(tbOrder.getUserId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "未绑定会员");
        }

        //订单状态为0-付款状态时，才能确认收货
        if(tbOrder.getStatus() == 0){
            //调用确认收货接口
            TbOrderSettledDto tbOrderSettledDto = new TbOrderSettledDto();
            tbOrderSettledDto.setMerId(tbOrder.getMerId());
            tbOrderSettledDto.setOrderId(tbOrder.getParentOrderNo());
            tbOrderSettledDto.setChildOrderId(tbOrder.getChildOrderNo());
            UzaiRespVo<Object> result =  tbOrderFeignService.settled(tbOrderSettledDto);

            logger.info("---发送修改淘宝订单确认收货-para={}, result={}", JSONObject.toJSONString(tbOrderSettledDto), JSONObject.toJSONString(result));

            if(result.getCode() != 200){
                throw  new BusinessException(result.getCode(), result.getMsg());
            }
        }
        return true;
    }

    /**
     * 手动维权
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param tbOrderDto
     * @return null
     */
    public Boolean confirmRefund(TbOrderDto tbOrderDto){
        try {

            if(tbOrderDto.getId() == null){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
            }

            //查询淘宝订单
            TbOrder tbOrder = tbOrderMapper.selectById(tbOrderDto.getId(), tbOrderDto.getMerId());

            if(tbOrder == null ){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.ORDER_IS_NULL);
            }

            //订单状态为1-结算状态时，才能手动维权
            if(tbOrder.getStatus() == 1){
                //调用确认维权接口
                return true;
            }
            return false;
        }catch (Exception e){
            logger.error("-----confirmRefund is error {}", e.getMessage());
            return false;
        }
    }

    /**
     * 订单冻结
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param tbOrderDto
     * @return null
     */
    public Boolean confirmFrozen(TbOrderDto tbOrderDto){
        try {

            if(tbOrderDto.getId() == null){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
            }

            //查询淘宝订单
            TbOrder tbOrder = tbOrderMapper.selectById(tbOrderDto.getId(), tbOrderDto.getMerId());

            if(tbOrder == null ){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.ORDER_IS_NULL);
            }

            //订单状态为0-付款状态时，才能冻结
            if(tbOrder.getStatus() == 0){
                //调用订单冻结接口
                return true;
            }

            return false;
        }catch (Exception e){
            logger.error("-----confirmFrozen is error {}", e.getMessage());
            return false;
        }
    }

    /**
     * 订单解冻
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param tbOrderDto
     * @return null
     */
    public Boolean confirmThaw(TbOrderDto tbOrderDto){

        if(tbOrderDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        //查询淘宝订单
        TbOrder tbOrder = tbOrderMapper.selectById(tbOrderDto.getId(), tbOrderDto.getMerId());

        if(tbOrder == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.ORDER_IS_NULL);
        }

        //订单返利状态为3-返利冻结时，才能解冻
        if(tbOrder.getReStatus() == 3){
            //调用确认解冻接口
            TbOrderUnfreezeDto tbOrderUnfreezeDto = new TbOrderUnfreezeDto();
            tbOrderUnfreezeDto.setMerId(tbOrder.getMerId());
            tbOrderUnfreezeDto.setOrderId(tbOrder.getParentOrderNo());
            tbOrderUnfreezeDto.setChildOrderId(tbOrder.getChildOrderNo());
            UzaiRespVo<Object> result =  tbOrderFeignService.unfreeze(tbOrderUnfreezeDto);

            logger.info("---发送修改淘宝订单解冻-para={}, result={}", JSONObject.toJSONString(tbOrderUnfreezeDto), JSONObject.toJSONString(result));

            if(result.getCode() != 200){
                throw  new BusinessException(result.getCode(), result.getMsg());
            }
        }
        return true;
    }

    /**
     * 订单解绑用户
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param tbOrderUnbindUserDto
     * @return null
     */
    public Boolean unbindUser(TbOrderUnbindUserDto tbOrderUnbindUserDto){

        if(tbOrderUnbindUserDto.getId() == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        //查询淘宝订单
        TbOrder tbOrder = tbOrderMapper.selectById(tbOrderUnbindUserDto.getId(), tbOrderUnbindUserDto.getMerId());

        if(tbOrder == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.ORDER_IS_NULL);
        }

        //订单未绑定用户
        if(tbOrder.getUserId() != null){
            //调用确认解绑接口
            TbOrderUnbindDto tbOrderUnbindDto = new TbOrderUnbindDto();
            tbOrderUnbindDto.setMerId(tbOrder.getMerId());
            tbOrderUnbindDto.setOrderId(tbOrder.getParentOrderNo());
            tbOrderUnbindDto.setChildOrderId(tbOrder.getChildOrderNo());
            UzaiRespVo<Object> result =  tbOrderFeignService.unbind(tbOrderUnbindDto);
            logger.info("---发送修改淘宝订单解绑用户-para={}, result={}", JSONObject.toJSONString(tbOrderUnbindDto), JSONObject.toJSONString(result));

            //AOP切面，封装操作日志内容
            String aspectOperatorLog = "淘宝订单解绑会员。订单号:"+tbOrder.getChildOrderNo()+";会员id：" + tbOrder.getUserId();
            tbOrderUnbindUserDto.setAspectOperatorLog(aspectOperatorLog);

            if(result.getCode() != 200){
                throw  new BusinessException(result.getCode(), result.getMsg());
            }
        }
        return true;
    }

    /**
     * 订单绑定用户
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param tbOrderBindUserDto
     * @return null
     */
    public Boolean bindUser(TbOrderBindUserDto tbOrderBindUserDto){

        if(tbOrderBindUserDto.getId() == null || tbOrderBindUserDto.getUserId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        //查询淘宝订单
        TbOrder tbOrder = tbOrderMapper.selectById(tbOrderBindUserDto.getId(), tbOrderBindUserDto.getMerId());

        if(tbOrder == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.ORDER_IS_NULL);
        }

        if(Tools.getInteger(tbOrder.getStatus()).intValue() != OrderStatusEnum.STATUS_PAID_VALUE){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "只有付款状态才能绑定会员");
        }

        //查询用户是否存在
        User user = userService.findUserInfo(tbOrderBindUserDto.getUserId(), tbOrder.getDeviceType(), tbOrderBindUserDto.getMerId());
        if(user == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.NO_USER);
        }

        //调用确认绑定用户接口
        TbOrderBindDto tbOrderBindDto = new TbOrderBindDto();
        tbOrderBindDto.setMerId(tbOrder.getMerId());
        tbOrderBindDto.setOrderId(tbOrder.getParentOrderNo());
        tbOrderBindDto.setChildOrderId(tbOrder.getChildOrderNo());
        tbOrderBindDto.setBizUserId(user.getBizUserId());
        tbOrderBindDto.setDeviceUniqueId(user.getDeviceUniqueId());
        tbOrderBindDto.setDeviceType(user.getRegSource());
        UzaiRespVo<Object> result =  tbOrderFeignService.bind(tbOrderBindDto);

        logger.info("---发送修改淘宝订单绑定会员-para={}, result={}", JSONObject.toJSONString(tbOrderBindDto), JSONObject.toJSONString(result));

        if(result.getCode() != 200){
            throw  new BusinessException(result.getCode(), result.getMsg());
        }

        //发送绑定订单异常提醒通知
        AlarmMsgFeignDto alarmMsgFeignDto = new AlarmMsgFeignDto();
        alarmMsgFeignDto.setMerId(tbOrderBindUserDto.getMerId());
        alarmMsgFeignDto.setType(SysMsgTypeEnum.OPE_UPDATE_ORDER_BIND.getValue()); //修改绑定订单会员
        //消息
        JSONObject ext = new JSONObject();
        //当前操作员
        String token_key = String.format(CacheKey.LOGIN_TOKEN, tbOrderBindUserDto.getLoginToken());
        Object data = redisTemplate.opsForValue().get(token_key);
        LoginVo loginVo = JSONObject.parseObject(String.valueOf(data), LoginVo.class);
        ext.put("childuser", loginVo.getLoginName());
        ext.put("orderid", tbOrder.getParentOrderNo());
        ext.put("nick", user.getNickName());
        ext.put("wxid", user.getBizUserId());
        alarmMsgFeignDto.setExt(ext.toJSONString());
//        UzaiRespVo uzaiRespVo = uzaiBroadcastFeignService.sysMsgPush(alarmMsgFeignDto);
//        logger.info("---发送修改订单绑定会员报警消息-para={}, result={}", JSONObject.toJSONString(alarmMsgFeignDto), JSONObject.toJSONString(uzaiRespVo));

        //2024-01-09修改成直接发送MQ
        noticeMsgPushProducerService.sendSysAlarmMsgAsync(alarmMsgFeignDto);

        return true;
    }

    /**
     * 修改解冻时间
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param tbOrderThawTimeDto
     * @return null
     */
    public Boolean updateThawTime(TbOrderThawTimeDto tbOrderThawTimeDto){
        try {
            if(tbOrderThawTimeDto.getId() == null || tbOrderThawTimeDto.getUnfreezeTime() == null){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
            }

            //查询淘宝订单
            TbOrder tbOrder = tbOrderMapper.selectById(tbOrderThawTimeDto.getId(), tbOrderThawTimeDto.getMerId());

            if(tbOrder == null ){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.ORDER_IS_NULL);
            }
            //设置修改时间
            tbOrderThawTimeDto.setUpdateTime(DateUtil.getNowTime());
            tbOrderMapper.updateThawTime(tbOrderThawTimeDto);
            return true;
        }catch (Exception e){
            logger.error("-----updateStateById is error {}", e.getMessage());
            return false;
        }
    }

    /**
     * 查询淘宝阿里妈妈联盟列表
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param tbTokenQuery
     * @return null
     */
    public List<TbOrderTokenVo> findTbTokenList(TbTokenQuery tbTokenQuery){
        //返利的对象
        List<TbOrderTokenVo> tbOrderTokenVoList = new ArrayList<TbOrderTokenVo>();
        //查询数据库中的阿里妈妈联盟账号
        List<TbToken> tbTokenList =  tbTokenMapper.findByList(tbTokenQuery);
        if(tbTokenList != null && tbTokenList.size() > 0){
            int now = DateUtil.getNowTime();
            for (TbToken tbToken : tbTokenList){
                TbOrderTokenVo tbOrderTokenVo = new TbOrderTokenVo();
                BeanUtils.copyProperties(tbToken,tbOrderTokenVo);
                if(tbToken.getExptime().intValue() <= now){
                    tbOrderTokenVo.setExptimeFlag(1); //已到期
                }else {
                    tbOrderTokenVo.setExptimeFlag(0); //未到期
                }
                tbOrderTokenVoList.add(tbOrderTokenVo);
            }
        }
        return tbOrderTokenVoList;
    }

    /**
     * 手动下载淘宝订单
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param tbOrderDownLoadDto
     * @return null
     */
    @Override
    public void downloadOrder(TbOrderDownLoadDto tbOrderDownLoadDto) {

        if (tbOrderDownLoadDto.getIdList() == null || tbOrderDownLoadDto.getIdList().size() == 0 || tbOrderDownLoadDto.getOrderScene() == null || tbOrderDownLoadDto.getQueryTimeType() == null
            || tbOrderDownLoadDto.getQueryStartTime() == null || tbOrderDownLoadDto.getQueryEndTime() == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        //判断开始时间是否小于90天前
        Integer now = DateUtil.getNowTime();
        if(now - tbOrderDownLoadDto.getQueryStartTime() > 7776000){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "开始时间不能小于90天前");
        }

        //日期范围只能是7天内
        if(tbOrderDownLoadDto.getQueryStartTime() < (tbOrderDownLoadDto.getQueryEndTime()-604800)){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "日期范围只能是7天内");
        }

        String val = (String) redisTemplate.opsForValue().get(String.format(CacheKey.TB_DOWNLOAD_ORDER_OPE, tbOrderDownLoadDto.getMerId()));

        if (StringUtils.isNotBlank(val)){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION,"2分钟只允许一次下载请求");
        }

        //异步后台调用订单远程下载
        tbOrderSyncService.downloadOrderListSync(tbOrderDownLoadDto);

        //往reids插入本次下载，允许5分钟下载一次，避免频繁提交
        redisTemplate.opsForValue().set(String.format(CacheKey.TB_DOWNLOAD_ORDER_OPE,tbOrderDownLoadDto.getMerId()),tbOrderDownLoadDto.getMerId()+"",2, TimeUnit.MINUTES);

    }

    /**
     * 手动下载淘宝订单(不入订单库，直接下载订单同步到业务库)
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param tbOrderDownLoadDto
     * @return null
     */
    @Override
    public void downloadOrder_notInStock(TbOrderDownLoadDto tbOrderDownLoadDto) {

        if (tbOrderDownLoadDto.getIdList() == null || tbOrderDownLoadDto.getIdList().size() == 0 || tbOrderDownLoadDto.getOrderScene() == null || tbOrderDownLoadDto.getQueryTimeType() == null
                || tbOrderDownLoadDto.getQueryStartTime() == null || tbOrderDownLoadDto.getQueryEndTime() == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        //判断开始时间是否小于90天前
        Integer now = DateUtil.getNowTime();
        if(tbOrderDownLoadDto.getOrderScene().intValue() != 4){
            if(now - tbOrderDownLoadDto.getQueryStartTime() > 7776000){
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "开始时间不能小于90天前");
            }

            //日期范围只能是2天内
            if(tbOrderDownLoadDto.getQueryStartTime() < (tbOrderDownLoadDto.getQueryEndTime()-2*24*3600)){
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "日期范围只能是2天内");
            }

            //当前运营商还有淘宝订单下载记录未执行完，请等待完成之后才能开始新的
            OrderPullQuery orderPullQuery = new OrderPullQuery();
            orderPullQuery.setMerId(tbOrderDownLoadDto.getMerId());
            orderPullQuery.setPlatform(OrderPullPlatformEnum.TB.getKey());
            Integer count = orderPullMapper.findCount(orderPullQuery);
            if(Tools.getInteger(count) > 0){ //还有下载记录，不能进行新的下载
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "上一次订单下载还未全部下载完成");
            }

        }else{
            if(tbOrderDownLoadDto.getQueryTimeType().intValue() == 4){ //订单创建时间
                if(tbOrderDownLoadDto.getQueryStartTime().intValue() <= 1672329600){ //维权订单按照创建时间拉取时，开始时间不能在2022年12月20日0之前
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "维权订单按创建时间拉取时，开始时间不能在2022年12月20日0点之前");
                }
            }

            //日期范围只能是31天内
            if(tbOrderDownLoadDto.getQueryStartTime() < (tbOrderDownLoadDto.getQueryEndTime()-31*24*3600)){
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "日期范围只能是一个月内");
            }

            //当前运营商还有淘宝维权订单下载记录未执行完，请等待完成之后才能开始新的
            OrderPullQuery orderPullQuery = new OrderPullQuery();
            orderPullQuery.setMerId(tbOrderDownLoadDto.getMerId());
            orderPullQuery.setPlatform(OrderPullPlatformEnum.TBWQ.getKey());
            Integer count = orderPullMapper.findCount(orderPullQuery);
            if(Tools.getInteger(count) > 0){ //还有下载记录，不能进行新的下载
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "上一次订单下载还未全部下载完成");
            }
        }

        String val = (String) redisTemplate.opsForValue().get(String.format(CacheKey.TB_DOWNLOAD_ORDER_OPE, tbOrderDownLoadDto.getMerId()));

        if (StringUtils.isNotBlank(val)){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION,"2分钟只允许一次下载请求");
        }

        //如果是订单创建时间查询（则将起始时间范围扩大30秒,防止淘客创建时间和淘宝创建时间不一样)
        if(Tools.getInteger(tbOrderDownLoadDto.getQueryTimeType()).intValue() == 1 || Tools.getInteger(tbOrderDownLoadDto.getQueryTimeType()).intValue() == 4){
            tbOrderDownLoadDto.setQueryStartTime(tbOrderDownLoadDto.getQueryStartTime()-30);
            tbOrderDownLoadDto.setQueryEndTime(tbOrderDownLoadDto.getQueryEndTime() + 30);
        }

        //异步后台调用订单远程下载
        tbOrderSyncService.downloadOrderListSync_notInStock(tbOrderDownLoadDto);

        //往reids插入本次下载，允许5分钟下载一次，避免频繁提交
        redisTemplate.opsForValue().set(String.format(CacheKey.TB_DOWNLOAD_ORDER_OPE,tbOrderDownLoadDto.getMerId()),tbOrderDownLoadDto.getMerId()+"",2, TimeUnit.MINUTES);

    }



    /**
     * 通过API手动下载淘宝订单
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param tbOrderApiDownLoadDto
     * @return null
     */
    public void downloadOrderApi(TbOrderApiDownLoadDto tbOrderApiDownLoadDto){
        if (tbOrderApiDownLoadDto.getIdList() == null || tbOrderApiDownLoadDto.getIdList().size() == 0 || tbOrderApiDownLoadDto.getOrderScene() == null || tbOrderApiDownLoadDto.getQueryTimeType() == null
                || tbOrderApiDownLoadDto.getQueryStartTime() == null || tbOrderApiDownLoadDto.getQueryEndTime() == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        //判断开始时间是否小于90天前
        Integer now = DateUtil.getNowTime();
        if(now - tbOrderApiDownLoadDto.getQueryStartTime() > 7776000){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "开始时间不能小于90天前");
        }

        //日期范围只能是7天内
        if(tbOrderApiDownLoadDto.getQueryStartTime() < (tbOrderApiDownLoadDto.getQueryEndTime() - 20*60)){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "日期范围只能是20分钟");
        }

        String val = (String) redisTemplate.opsForValue().get(String.format(CacheKey.TB_DOWNLOAD_ORDER_API, tbOrderApiDownLoadDto.getMerId()));

        if (StringUtils.isNotBlank(val)){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION,"提交频繁，请30秒后重新提交！");
        }

        //异步后台调用订单远程下载
        tbOrderSyncService.downloadOrderApiListSync(tbOrderApiDownLoadDto);

        //往reids插入本次下载，允许5分钟下载一次，避免频繁提交
        redisTemplate.opsForValue().set(String.format(CacheKey.TB_DOWNLOAD_ORDER_API, tbOrderApiDownLoadDto.getMerId()),tbOrderApiDownLoadDto.getMerId()+"",30, TimeUnit.SECONDS);
    }


    /**
     * 刷新淘宝订单
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param tbOrderDto
     * @return null
     */
    @Override
    public void refreshOrder(TbOrderDto tbOrderDto){
        if (tbOrderDto.getId() == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }
        TbOrder tbOrder =  tbOrderMapper.selectById(tbOrderDto.getId(), tbOrderDto.getMerId());
        //判断订单存在或者已删除
        if(tbOrder == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION,"该订单不存在或是3个月之前的历史订单");
        }

        //判断开始时间是否小于90天前
        Integer now = DateUtil.getNowTime();
        if(now - tbOrder.getCreatedt() > 7776000){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "由于接口限制，只能同步90天内的订单！");
        }

        if(tbOrderDto.getMerId().longValue() != 1547482020152213506L){
            String val = (String) redisTemplate.opsForValue().get(String.format(CacheKey.TB_REFRESH_ORDER_OPE, tbOrder.getMerId()));
            if (StringUtils.isNotBlank(val)){
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION,"5分钟只允许一次刷新请求");
            }
        }

        //异步后台调用订单远程下载
        tbOrderSyncService.updateTbOrder(tbOrder);

        //往reids插入本次下载，允许5分钟下载一次，避免频繁提交
        redisTemplate.opsForValue().set(String.format(CacheKey.TB_REFRESH_ORDER_OPE, tbOrder.getMerId()),tbOrder.getMerId()+"",5, TimeUnit.MINUTES);
    }



    /**
     * 查询所有未绑定用户订单列表
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param tbOrderUnbindDtoQuery
     * @return null
     */
    public Page<TbOrderInfoVo> findUnbindUserList(TbOrderUnbindDtoQuery tbOrderUnbindDtoQuery){

        List<TbOrderInfoVo> tbOrderInfoVoList = new ArrayList<>();

        Page<TbOrder> page = new Page<>();
        tbOrderUnbindDtoQuery.convert(page);
        ArrayList<TbOrder> tbOrderList =  tbOrderMapper.findUnbindUserList(page, tbOrderUnbindDtoQuery);
        if(tbOrderList != null && tbOrderList.size() > 0){
            for (TbOrder tbOrder : tbOrderList){

                TbOrderInfoVo tbOrderInfoVo = new TbOrderInfoVo();
                BeanUtils.copyProperties(tbOrder, tbOrderInfoVo);
                //查询机器人信息
                Device device = deviceService.findDeviceInfoByDeviceUniqueId(tbOrder.getDeviceUniqueId(), tbOrder.getDeviceType(), tbOrder.getMerId());
                if(device != null){
                    tbOrderInfoVo.setDeviceId(device.getDeviceId());
                    tbOrderInfoVo.setDeviceName(device.getDeviceName());
                    tbOrderInfoVo.setDeviceRemark(device.getDeviceRemark());
                }
                tbOrderInfoVoList.add(tbOrderInfoVo);
            }
        }
        //返回到页面分页对象
        Page<TbOrderInfoVo> pageVo = new Page<>();
        BeanUtils.copyProperties(page, pageVo);
        pageVo.setRecords(tbOrderInfoVoList);
        //将分页信息复制到返回到页面的分页MO当中
        return pageVo;
    }

    /**
     * 查询所有未绑定用户订单统计信息
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param tbOrderUnbindDtoQuery
     * @return null
     */
    public TbOrderReportVo findUnbindUserReport(TbOrderUnbindDtoQuery tbOrderUnbindDtoQuery){
        return tbOrderMapper.findUnbindUserReport(tbOrderUnbindDtoQuery);
    }

    /**
     * 删除所有未绑定用户订单-假删除（修改是否删除状态）
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param tbOrderDeleteUnbindDto
     * @return tbOrderUnbindDtoQuery
     */
    public Boolean deleteUnbindUserList(TbOrderDeleteUnbindDto tbOrderDeleteUnbindDto){
        try {
            tbOrderMapper.deleteUnbindUserList(tbOrderDeleteUnbindDto);
            return true;
        }catch (Exception e){
            logger.error("-----deleteUnbindUserList is error {}", e.getMessage());
            return false;
        }
    }

    /**
     * 更新7天前未收货订单
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param merId
     * @return null
     */
    public void updateTbOrderUnReceivedList(Long merId){

        if (merId == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        //从redis中获取上次更新的时间，判断12小时执行一次
        Object val = redisTemplate.opsForValue().get(String.format(CacheKey.TB_UPDATE_ORDER_OPE, merId));
        if (val != null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "12小时内只能更新一次");
        }

        //异步调用，更新7天前所有未收货的订单
        tbOrderSyncService.updateTbOrderUnReceivedListSync(merId);

        //将本次更新操作记录到Redis当中，下次更新需要12个小时以后操作
        redisTemplate.opsForValue().set(String.format(CacheKey.TB_UPDATE_ORDER_OPE,merId),merId,12, TimeUnit.HOURS);

    }

    /**
     * 上传淘宝维权订单
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param tbRefundOrderExcelDemoList
     * @return null
     */
    public void uploadTbPunishOrderFile(List<TbRefundOrderExcelDemo> tbRefundOrderExcelDemoList){
        //异步后台调用订单远程下载
        tbOrderSyncService.uploadTbRefundOrderSync(tbRefundOrderExcelDemoList);
    }


    /**
     * 追回返利
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param tbOrderDto
     * @return null
     */
    @Transactional
    public Boolean rebateRefound(TbOrderDto tbOrderDto){

        if(tbOrderDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入id");
        }

        //是否是正常订单标志
        boolean orderFlag = true; //订单标志（true-正常订单；false-历史订单）

        //查询淘宝订单
        TbOrder tbOrder = tbOrderMapper.selectById(tbOrderDto.getId(), tbOrderDto.getMerId());

        String tableSuffix = null;

        //如果为空，则从历史订单中查询
        if(tbOrder == null){
            if(tbOrderDto.getCreatedt() == null){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入订单创建时间");
            }
            tableSuffix = DateTime.of(tbOrderDto.getCreatedt() * 1000L).toString("yyMM");
            UzaiRespVo<TbOrder> uzaiRespVo = historyDataFeignService.getTbOrder(tableSuffix, tbOrderDto.getId(), tbOrderDto.getMerId());
            if(uzaiRespVo != null && uzaiRespVo.getData() != null){
                tbOrder = uzaiRespVo.getData();
                orderFlag = false; //历史订单标志
            }
        }

        if(tbOrder == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该订单不存在");
        }

        if(tbOrder.getReStatus() != 1){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该订单状态不是已返利状态");
        }

        //修改订单结果
        boolean updateStatus = false;

        int now = DateUtil.getNowTime();

        //正常订单，立即修改
        if(orderFlag){
            tbOrder.setStatus(OrderStatusEnum.STATUS_REFUND_SUCCESS_VALUE); //维权成功
            tbOrder.setReStatus(OrderReStatusEnum.RE_STATUS_BACK_VALUE);    //已追回
            tbOrder.setRefundCreateTime(now);
            tbOrder.setRefundFinishTime(now);
            tbOrder.setUpdateTime(now);
            int i = tbOrderMapper.updateStatus(tbOrder);
            //修改状态成功
            if(i == 1){
                updateStatus = true;
            }
        }else{//历史订单，调用接口修改
            HistoryTbOrderOptDto historyTbOrderOptDto = new HistoryTbOrderOptDto();
            BeanUtils.copyProperties(tbOrder, historyTbOrderOptDto);
            historyTbOrderOptDto.setId(tbOrder.getId());
            historyTbOrderOptDto.setMerId(tbOrder.getMerId());
            historyTbOrderOptDto.setStatus(OrderStatusEnum.STATUS_REFUND_SUCCESS_VALUE); //维权成功
            historyTbOrderOptDto.setReStatus(OrderReStatusEnum.RE_STATUS_BACK_VALUE);    //已追回
            historyTbOrderOptDto.setRefundCreateTime(now);
            historyTbOrderOptDto.setRefundFinishTime(now);
            UzaiRespVo<Boolean> uzaiRespVo = historyDataFeignService.edit(tableSuffix, historyTbOrderOptDto);
            logger.info("--调用淘宝历史订单处理追回返利接口--tableSuffix={}, para={}, result={}",tableSuffix, JSONObject.toJSONString(tableSuffix), JSONObject.toJSONString(tableSuffix));
            //修改状态成功
            if(uzaiRespVo != null && uzaiRespVo.getData()){
                updateStatus = true;
            }
        }

        //修改成功，处理账户余额
        if(updateStatus){
            //绑定会员
            if(tbOrder.getUserId() != null){
                //运营商id
                Long merId = tbOrder.getMerId();
                //父订单号
                String parentOrderNo = tbOrder.getParentOrderNo();
                //子订单号
                String childOrderNo = tbOrder.getChildOrderNo();
                //会员id
                Long userId = tbOrder.getUserId();
                //机器人类型
                String deviceType = tbOrder.getDeviceType();
                //机器人唯一id
                Long deviceUniqueId = tbOrder.getDeviceUniqueId();
                //用户积分
                int reUserInte = Tools.getInteger(tbOrder.getReUserInte());
                //用户返利
                double reUserBal = tbOrder.getReUserBal();
                //上级返利
                double reParentUserBal = tbOrder.getReParentBal();
                //上上级返利
                double reSlParentUserBal = tbOrder.getReSlParentBal();
                //代理返利
                double reAgentBal = tbOrder.getReAgentBal();
                //上级代理返利
                double reSlAgentBal = tbOrder.getReSlAgentBal();
                //合伙人返利
                double rePartnerBal = tbOrder.getRePartnerBal();

                //追回返利
                BaseOrderVo baseOrderVo = new BaseOrderVo();
                BeanUtils.copyProperties(tbOrder, baseOrderVo);
                userAccDetailService.updateByRebateRefound(merId, parentOrderNo, childOrderNo, userId, deviceType, deviceUniqueId,
                        reUserInte, reUserBal, reParentUserBal, reSlParentUserBal, reAgentBal, reSlAgentBal, rePartnerBal, now, baseOrderVo);
            }
        }

        return true;
    }

    /**
     * 淘宝订单查询结果导出数据
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param tbOrderExportResultDto
     * @return null
     */
    public void exportByQeuryResult(TbOrderExportResultDto tbOrderExportResultDto){
        if(tbOrderExportResultDto.getMerId() == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        if(StringUtils.isBlank(tbOrderExportResultDto.getCode())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入验证码");
        }

        Merchant merchant = merchantMapper.selectById(tbOrderExportResultDto.getMerId());
        if(merchant == null ){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "运营商不存在");
        }

        //测试服方便测试，抛弃10分钟限流
        if(tbOrderExportResultDto.getMerId() != 1547482020152213506L) {
            Object val = redisTemplate.opsForValue().get(String.format(CacheKey.TB_ORDER_EXPORT, tbOrderExportResultDto.getMerId()));
            if (!Objects.isNull(val)) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "10分钟只允许请求一次");
            }
        }

        //查询输入的验证码是否为系统默认密码
        if(!tbOrderExportResultDto.getCode().equals(uzaiConsoleSysConfig.getDefaultPassword())){
            //获取存在redis中的验证码
            String codeKey = String.format(SmsType.SPECIAL_OPERATE.getDesc(), merchant.getMobile());
            String codeByRedis = (String) redisTemplate.opsForValue().get(codeKey);
            //判断验证码是否过期
            if (StringUtils.isBlank(codeByRedis)){
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.CODE_MISS);
            }

            //验证码是否正确
            if (!codeByRedis.equals(tbOrderExportResultDto.getCode())){
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.CODE_ERR);
            }

            //验证成功，删除验证码
            redisTemplate.delete(codeKey);
        }

        //计算费用
        TbOrderQuery tbOrderQuery = tbOrderExportResultDto.getTbOrderQuery();
        tbOrderQuery.setMerId(tbOrderExportResultDto.getMerId());
        ExportAmountVo exportAmountVo = tbOrderSyncService.getExportAmount(tbOrderQuery);
        //判断余额大小
        Double balance = merchant.getBalance();
        if(balance.doubleValue() < exportAmountVo.getAmountTotal()){ //不够支付
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "账户余额不足");
        }

        //执行异步导出淘宝订单
        tbOrderSyncService.exportTbOrderSync(tbOrderExportResultDto);

        //往reids插入本次下载，允许10分钟请求一次，避免频繁提交
        redisTemplate.opsForValue().set(String.format(CacheKey.TB_ORDER_EXPORT, tbOrderExportResultDto.getMerId()),tbOrderExportResultDto.getMerId(),10, TimeUnit.MINUTES);

    }

}
